package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.IntentSender;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.picselect.entity.SelectMediaEntity;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelAlbumAdapter;
import flc.ast.adapter.SelEditAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.bean.MyCollectBean;
import flc.ast.bean.MySelEditBean;
import flc.ast.databinding.ActivityViewPictureBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.ToastUtil;
import stark.common.basic.view.container.StkLinearLayout;
import stark.common.basic.view.container.StkRecycleView;

public class ViewPictureActivity extends BaseAc<ActivityViewPictureBinding> {

    public static SelectMediaEntity selectMediaEntity;
    private SelEditAdapter selEditAdapter;
    private Dialog mySeleditDialog;
    private int editPos, albumPos;
    private boolean isCollect = false;
    //删除相册图片
    public final int REQUEST_CODE_DELETE_IMAGE = 1000;
    private SelAlbumAdapter selAlbumAdapter;
    private Dialog mySelAlbumDialog;
    private Dialog myAddAlbumDialog;
    private EditText dialogAdd;

    @Override
    protected int onCreate() {
        return R.layout.activity_view_picture;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivViewPictureBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivViewPictureEdit.setOnClickListener(this);
        mDataBinding.ivDelete.setOnClickListener(this);
        mDataBinding.ivCollect.setOnClickListener(this);
        mDataBinding.ivAdd.setOnClickListener(this);

        selEditAdapter = new SelEditAdapter();
        selEditAdapter.setOnItemClickListener(this);

        selAlbumAdapter = new SelAlbumAdapter();
        selAlbumAdapter.setOnItemClickListener(this);

        Glide.with(mContext).load(selectMediaEntity.getPath()).into(mDataBinding.ivViewPictureImg);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivDelete://删除
                deletePicture();
                break;
            case R.id.ivCollect://收藏
                List<MyCollectBean> listSp = AppSpUtils.getCollectList();
                if (isCollect) {
                    listSp.remove(new MyCollectBean(selectMediaEntity.getPath(), false));
                    AppSpUtils.saveCollectList(listSp);
                    isCollect = false;
                } else {
                    if (listSp != null && listSp.size() > 0) {
                        listSp.add(new MyCollectBean(selectMediaEntity.getPath(), false));
                        AppSpUtils.saveCollectList(listSp);
                    } else {
                        List<MyCollectBean> listSave = new ArrayList<>();
                        listSave.add(new MyCollectBean(selectMediaEntity.getPath(), false));
                        AppSpUtils.saveCollectList(listSave);
                    }
                    isCollect = true;
                }
                isCollect();
                break;
            case R.id.ivViewPictureEdit://编辑
                mySeleditDialog.show();
                break;
            //选择编辑弹框
            case R.id.ivDialogSelEditCancel://取消
                mySeleditDialog.dismiss();
                break;
            case R.id.tvDialogSelEditConfirm://确定
                if (editPos == 0) {
                    AddFilterActivity.imgPath = selectMediaEntity.getPath();
                    startActivity(AddFilterActivity.class);
                } else if (editPos == 1) {
                    AddStickerActivity.imgPath = selectMediaEntity.getPath();
                    startActivity(AddStickerActivity.class);
                } else if (editPos == 2) {
                    AddTextActivity.imgPath = selectMediaEntity.getPath();
                    startActivity(AddTextActivity.class);
                } else if (editPos == 3) {
                    AddBackgroundActivity.imgPath = selectMediaEntity.getPath();
                    startActivity(AddBackgroundActivity.class);
                }
                mySeleditDialog.dismiss();
                break;
            case R.id.ivAdd://添加到
                getAlbumData();
                mySelAlbumDialog.show();
                break;
            //选择相册弹框
            case R.id.ivDialogSelAlbumCancel://取消
                mySelAlbumDialog.dismiss();
                break;
            case R.id.tvDialogSelAlbumConfirm://确定
                List<MyAlbumBean> listSp1 = AppSpUtils.getAlbumList();
                listSp1.get(albumPos).getListData().add(selectMediaEntity.getPath());
                AppSpUtils.saveAlbumList(listSp1);
                mySelAlbumDialog.dismiss();
                break;
            case R.id.llDialogSelAlbumAdd://新建相册
                //新建相册弹框
                addAlbumDialog();
                myAddAlbumDialog.show();
                break;
            //新建相册弹框
            case R.id.tvDialogAddAlbumConfirm://确定
                addAlbum();
                break;
            case R.id.ivDialogAddAlbumCancel://取消
                myAddAlbumDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == selEditAdapter) {
            selEditAdapter.getItem(editPos).setSelected(false);
            editPos = position;
            selEditAdapter.getItem(position).setSelected(true);
            selEditAdapter.notifyDataSetChanged();
        } else if (adapter == selAlbumAdapter) {
            selAlbumAdapter.getItem(albumPos).setSelected(false);
            albumPos = position;
            selAlbumAdapter.getItem(position).setSelected(true);
            selAlbumAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void initData() {
        List<MySelEditBean> listEdit = new ArrayList<>();
        listEdit.add(new MySelEditBean(getString(R.string.add_filter), true));
        listEdit.add(new MySelEditBean(getString(R.string.add_sticker), false));
        listEdit.add(new MySelEditBean(getString(R.string.add_text), false));
        listEdit.add(new MySelEditBean(getString(R.string.add_background), false));
        selEditAdapter.setList(listEdit);
        //选择编辑弹框
        selEditDialog();
        List<MyCollectBean> listSp = AppSpUtils.getCollectList();
        if (listSp != null && listSp.size() > 0) {
            if (listSp.contains(new MyCollectBean(selectMediaEntity.getPath(), false))) {
                isCollect = true;
            }
        }
        isCollect();
        //选择相册弹框
        selAlbumDialog();
    }

    private void isCollect() {
        if (isCollect) {
            mDataBinding.ivCollect.setImageResource(R.drawable.an_sc1a);
        } else {
            mDataBinding.ivCollect.setImageResource(R.drawable.an_sc1);
        }
    }

    private void getAlbumData() {
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.get(0).setSelected(true);
            selAlbumAdapter.setList(listSp);
        }
    }

    //适配android11以上删除相册文件方式
    private void deletePicture() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            List<Uri> uris = new ArrayList<>(); // 这里存放所有需要删除的图片的uri
            uris.add(Uri.parse(selectMediaEntity.getUri()));
            PendingIntent pi = MediaStore.createDeleteRequest(getContentResolver(), uris);
            try {
                startIntentSenderForResult(pi.getIntentSender(), REQUEST_CODE_DELETE_IMAGE, null, 0, 0, 0);
            } catch (IntentSender.SendIntentException e) {
                Log.e("TAG", "startIntentSender error:" + e.toString());
            }
        } else {
            getContentResolver().delete(Uri.parse(selectMediaEntity.getUri()), null, null);
        }
        finish();
    }

    private void addAlbum() {
        String albumName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(albumName)) {
            ToastUtils.showShort(R.string.please_input_album_name);
            return;
        }
        myAddAlbumDialog.dismiss();
        //准备数据
        List<MyAlbumBean> listSave = new ArrayList<>();
        listSave.add(new MyAlbumBean(TimeUtils.getNowString(), albumName, new ArrayList<>(), false));
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveAlbumList(listSp);
        } else {
            AppSpUtils.saveAlbumList(listSave);
        }
        getAlbumData();
    }

    //选择编辑弹框
    private void selEditDialog() {
        mySeleditDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_edit, null);
        mySeleditDialog.setContentView(inflate);
        mySeleditDialog.setCancelable(true);
        Window dialogWindow = mySeleditDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogSelEditConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogSelEditCancel);
        StkRecycleView recycleView = inflate.findViewById(R.id.rvSelEditList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        recycleView.setAdapter(selEditAdapter);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //选择相册弹框
    private void selAlbumDialog() {
        mySelAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_sel_album, null);
        mySelAlbumDialog.setContentView(inflate);
        mySelAlbumDialog.setCancelable(true);
        Window dialogWindow = mySelAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogSelAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogSelAlbumCancel);
        StkLinearLayout add = inflate.findViewById(R.id.llDialogSelAlbumAdd);
        StkRecycleView recycleView = inflate.findViewById(R.id.rvSelAlbumList);
        recycleView.setLayoutManager(new LinearLayoutManager(mContext));
        recycleView.setAdapter(selAlbumAdapter);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
        add.setOnClickListener(this);
    }

    //新建相册弹框
    private void addAlbumDialog() {
        myAddAlbumDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddAlbumDialog.setContentView(inflate);
        myAddAlbumDialog.setCancelable(true);
        Window dialogWindow = myAddAlbumDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddAlbumConfirm);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddAlbumCancel);
        TextView num = inflate.findViewById(R.id.tvDialogAddAlbumNum);
        num.setText(getString(R.string.input_name_num, 0));
        dialogAdd = inflate.findViewById(R.id.etDialogAddAlbumText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialogAdd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                num.setText(getString(R.string.input_name_num, s.length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

}